package com.leefine.nettysocketproxy.config;


import com.leefine.nettysocketproxy.support.Util;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * AuthInterceptor
 *
 * Api Auth Interceptor
 *
 * @Author lihuai.chen@163.com
 * @Date 6/10/2021 11:59 AM
 */
public class AuthInterceptor implements HandlerInterceptor {

    private final static String API_SESSION_KEY = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter(API_SESSION_KEY);
        if (!Util.checkToken(token)) {
            response.getWriter().write(ApiResult.contruct(505, "Authentication failed!").toJson());
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}